import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/check_in_record/visitor_list/bean/visitor_list_response_bean.dart';
import 'package:e_reception_flutter/ui/check_in_record/visitor_list/visitor_list_view_model.dart';
import 'package:e_reception_flutter/ui/check_in_record/visitor_list/widgets/visitor_list_item_widget.dart';
import 'package:e_reception_flutter/ui/mark/matching_mark_list/matching_mark_list_page.dart';
import 'package:e_reception_flutter/ui/mark/matching_or_mark/bean/mark_info_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/bean/terminal_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

/// 访客列表
///
/// @author: zengxiangxi
/// @createTime: 3/29/21 2:29 PM
/// @specialDemand:
class VisitorListPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "VisitorListPage";


  final DateTime currentDateTime;

  const VisitorListPage({Key key, this.currentDateTime}) : super(key: key);

  @override
  _VisitorListPageState createState() => _VisitorListPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context,DateTime currentDateTime) {
    return RouterUtils.routeForFutureResult(
      context,
      VisitorListPage(
        currentDateTime: currentDateTime,
      ),
      routeName: VisitorListPage.ROUTER,
    );
  }
}

const double VISITOR_LIST_ITEM_HEIGHT = 60.0;

class _VisitorListPageState extends BaseState<VisitorListPage> {

  VisitorListViewModel _viewModel;

  CommonListPageWidgetState<VisitorListItemBean, VisitorListResponseBean>
      _state;

  ScrollController _scrollController;

  bool _isScroll = false;

  @override
  void initState() {
    super.initState();
    _viewModel = VisitorListViewModel(this);
    _scrollController =  ScrollController();
  }

  @override
  void dispose() {
    _scrollController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _toMainColumnWidget(),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        Expanded(
          child: _toListWidget(),
        ),
      ],
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      isShowBack: true,
      title: "访客",
    );
  }

  Widget _toListWidget() {
    return ScrollConfiguration(
      behavior: MyBehavior(),
      child: CommonListPageWidget<VisitorListItemBean, VisitorListResponseBean>(
        enablePullUp: false,
        enablePullDown: true,
        scrollController: _scrollController,
        physics: ClampingScrollPhysics(),
        queryMapFunc: (int page) => {
          "authId": UserRepository.getInstance().authId ?? "",
        },
        cacheExtent: VISITOR_LIST_ITEM_HEIGHT,
        parseDataFunc: (VgHttpResponse resp) {
          return VisitorListResponseBean.fromMap(resp?.data);
        },
        stateFunc: (CommonListPageWidgetState<VisitorListItemBean,
                VisitorListResponseBean>
            state) {
          _state = state;
        },
        listFunc: (List<VisitorListItemBean> list) {
          //测试滚动到一定位置
          _animateToPosition();
        },
        itemBuilder: (BuildContext context, int index, itemBean) {
          return VisitorListItemWidget(
            itemBean: itemBean,
            // onTap: () async {
              //跳转到匹配标记列表
              // bool result = await MatchingMarkListPage.navigatorPush(
              //     context,
              //     MarkInfoBean(
              //       picurl: itemBean?.pictureUrl,
              //       fid: itemBean?.fid,
              //     ));
              // if (result ?? false) {
              //   _state?.viewModel?.refreshMultiPage();
              // }
            // },
            onFaceIgnore: (VisitorListItemBean itemBean) async {
              bool result =
              await CommonConfirmCancelDialog.navigatorPushDialog(context,
                  title: "提示",
                  content: "确定忽略该用户？",
                  cancelText: "取消",
                  confirmText: "忽略",
                  confirmBgColor: ThemeRepository.getInstance()
                      .getMinorRedColor_F95355());
              if (result ?? false) {
                _viewModel?.ignoreSingleFaceHttp(context, itemBean?.fid,(){
                  _state?.viewModel?.refreshMultiPage();
                });
              }
            },
            onFaceDelete: (VisitorListItemBean itemBean) async {
              bool result =
              await CommonConfirmCancelDialog.navigatorPushDialog(context,
                  title: "提示",
                  content: "确定删除该用户？",
                  cancelText: "取消",
                  confirmText: "忽略",
                  confirmBgColor: ThemeRepository.getInstance()
                      .getMinorRedColor_F95355());
              if (result ?? false) {
                _viewModel?.deleteSingleFaceHttp(context, itemBean?.fid,(){
                  _state?.viewModel?.refreshMultiPage();
                });
              }
            },
          );
        },
        netUrl:ServerApi.BASE_URL + "app/appVisitorList",
        httpType: VgHttpType.get,
      ),
    );
  }

  ///动画滑动到位置
  void _animateToPosition(){
    if(_isScroll){
      return;
    }
    _isScroll = true;

    Future.delayed(Duration(milliseconds: 300),(){
      final int index = _getScrollPosition();
      if(index == null || index < 0){
        return;
      }
      _scrollController?.animateTo(index * VISITOR_LIST_ITEM_HEIGHT, duration: DEFAULT_ANIM_DURATION, curve: Curves.easeIn);
    });
  }

  ///获取需要滚动的位置（算法计算）
  int _getScrollPosition(){
    final List<VisitorListItemBean> list = _state?.data;
    if(list == null || list.isEmpty){
      return null;
    }
    final int currentTimeStamp = (widget.currentDateTime.millisecondsSinceEpoch / 1000).floor();
    ///相近日期
    int similarPosition;
    int i = -1;
    for(VisitorListItemBean item in list){
      i++;
      if(item == null || item.firsttime == null){
        continue;
      }
      if(VgDateTimeUtils.isEqualDay(currentTimeStamp,item.firsttime )){
        return i;
      }
      if(VgDateTimeUtils.isBig(item.firsttime,currentTimeStamp)){
        similarPosition = i;
        continue;
      }
      if(VgDateTimeUtils.isSmall(item.firsttime,currentTimeStamp)){
        return similarPosition;
      }
    }
    return similarPosition;
  }
}
